package com.alibaba.algo.schedule;

import com.alibaba.algo.apiimpl.user.SysRoleServiceImpl;
import com.alibaba.algo.apiimpl.user.SysUserCacheServiceImpl;
import com.alibaba.algo.util.DateUtil;
import com.alibaba.algo.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class SaticScheduleTask {

    @Autowired
    private SysUserCacheServiceImpl sysUserCacheService;
    @Autowired
    private SysRoleServiceImpl sysRoleService;

    /**
     * 每5分钟执行一次失败重新删除
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void reDeleteCache() {
        log.info("reDeleteCache start");
        try {
            sysUserCacheService.reDeleteUserInfoFromCache();
        } catch (Exception ex) {
            log.error("reDeleteCache exception", ex);
        }
        log.info("reDeleteCache end");
    }

    /**
     * 每日凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateUserRoleRelatedByOrgRole() {
        log.info("updateUserRoleRelatedByOrgRole start");
        try {
            String currentDate = DateUtil.format(new Date(), DateUtil.DEFAULT_DATE_FORMAT);
            String key = String.format("UpdOrgRole.%s", currentDate);
            log.info("updateUserRoleRelatedByOrgRole key={}", key);
            boolean isOk = JedisUtil.setnx(key, key, 3600);
            log.info("updateUserRoleRelatedByOrgRole result={}", isOk);
            if (isOk) {
                sysRoleService.updateUserRoleRelatedByOrgRole();
            }
        } catch (Exception ex) {
            log.error("updateUserRoleRelatedByOrgRole exception", ex);
        }
        log.info("updateUserRoleRelatedByOrgRole end");
    }
}
